﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoCADDotNetLibrary.Generator.Receiver;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace AutoCADDotNetLibrary.Generator
{
    [Generator]
    public class ExtensionApplicationAttributeGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context)
        {
            context.RegisterForSyntaxNotifications(() => new IExtensionApplicationSyntaxReceiver());
        }

        public void Execute(GeneratorExecutionContext context)
        {
            if (!(context.SyntaxContextReceiver is IExtensionApplicationSyntaxReceiver receiver))
                return;

            List<string> types = receiver.Types.Select(x => x.ToDisplayString()).ToList();

            if (types.Count != 1)
                return;

            //生成代码
            StringBuilder source = new StringBuilder("using Autodesk.AutoCAD.Runtime;");
            source.AppendLine();
            source.AppendLine();
            source.AppendLine($"[assembly: ExtensionApplication(typeof({types[0]}))]");

            context.AddSource("ExtensionApplicationAttributeGenerator.g.cs", SourceText.From(source.ToString(), Encoding.UTF8));
        }
    }
}
